<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Http\Controllers;


use App\Common\HttpClient;
use App\Common\Tool;
use App\Exceptions\ApiException;
use App\Logic\MiGuLogic;
use App\Model\MallConf\TicketMallConf;
use Illuminate\Support\Facades\DB;

class BuyTicket extends Base
{

    public function handle()
    {
        $data = TicketMallConf::where('id',$this->param['id'])->where('status',1)->first(['price','ticket']);
        if(empty($data)) {
            throw new ApiException('商品不存在');
        }
        $data = $data->toArray();
        $request              = [
            'gameId' => MiGuLogic::$gameID,
            'timestamp' => (string)Tool::msectime(),
            'userId' => (string)Tool::getMiGuId($this->uid),
            'operateTypeSub' => 2,
            'localPropDst' => 100004,
            'localPropNum' => $data['price'],
            'localScaleNum' => 1,
            'thirdGameName' => '贵州麻将',
            'thirdPropId' => 110000,
            'thirdPropName' => '房卡',
            'thirdPropNum' => $data['ticket'],
            'thirdScaleNum' => 10
        ];
        $request['signature'] = Tool::miGuSignature($request);
        $response             = (new HttpClient())->MiGuPost(env('MIGU_BASE_URL') . '/exchange/diamondRoomCard', json_encode($request));
        $response             = json_decode($response, true);
        if ($response['returnCode'] != '000000') {
            throw new ApiException($response['message'],$response['returnCode']);
        }
        DB::table('t_user_diamonds_rec')->insert([
            'uid' => $this->uid,
            'num' => $data['price'],
            'source' => '钻石兑换房卡',
            'comment' => 'diamonds:'.$data['price'].'-'.'room_card:'.$data['ticket'].'serialNo:'.$response['resultData']['serialNo']
        ]);
        return $this->returnData([
            'currentDiamonds' => $response['resultData']['currentDiamonds'],
            'currentRoomCards' => $response['resultData']['currentRoomCards']
        ]);
    }

}